template <class T> void SAFE_RELEASE(T** ppT)
{
	if (*ppT)
	{
		(*ppT)->Release();
		*ppT = NULL;
	}
}

BOOL CreateBitmapFromFile(ID2D1HwndRenderTarget* renderTarget, const char* fileName)
{
	HRESULT hr = S_OK;
	IWICBitmapDecoder* pDecoder = NULL;
	IWICBitmapFrameDecode* pSource = NULL;
	IWICStream* pStream = NULL;
	IWICFormatConverter* pConverter = NULL;
	IWICImagingFactory* imageFactory = NULL;

	//为了兼容win7、win10，这里采用CLSID_WICImagingFactory1
	if (NULL == imageFactory) {
		hr = CoInitialize(NULL);
		if (FAILED(hr)) {
			return FALSE;
		}
		hr = CoCreateInstance(
			CLSID_WICImagingFactory1,
			NULL,
			CLSCTX_INPROC_SERVER,
			IID_IWICImagingFactory,
			(LPVOID*)&imageFactory
		);
	}
	if (FAILED(hr))
	{
		return FALSE;
	}
	//创建wic解码器
	hr = imageFactory->CreateDecoderFromFilename(
		CString(fileName),
		NULL,
		GENERIC_READ,
		WICDecodeMetadataCacheOnLoad,
		&pDecoder
	);
	if (SUCCEEDED(hr))
	{
		hr = pDecoder->GetFrame(0, &pSource);
	}
	else
	{
		return FALSE;
	}
	if (SUCCEEDED(hr))
	{
		// Convert the image format to 32bppPBGRA
		// (DXGI_FORMAT_B8G8R8A8_UNORM + D2D1_ALPHA_MODE_PREMULTIPLIED).
		hr = imageFactory->CreateFormatConverter(&pConverter);
	}
	if (!SUCCEEDED(hr))
	{
		return FALSE;
	}
	hr = pConverter->Initialize(
		pSource,
		GUID_WICPixelFormat32bppPBGRA,
		WICBitmapDitherTypeNone,
		NULL,
		0.f,
		WICBitmapPaletteTypeMedianCut
	);
	if (SUCCEEDED(hr))
	{
		// Create a Direct2D bitmap from the WIC bitmap.
		//这里需要将wic位图转换成Direct2D位图
		hr = renderTarget->CreateBitmapFromWicBitmap(
			pConverter,
			NULL,
			&ppBitmap
		);
		if (FAILED(hr))
		{
			return FALSE;
		}
	}

	SAFE_RELEASE(&pDecoder);
	SAFE_RELEASE(&pSource);
	SAFE_RELEASE(&pStream);
	SAFE_RELEASE(&pConverter);
	return TRUE;
}